﻿using Aliyun.Acs.Core;
using Newtonsoft.Json;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using AhCha.Fortunate.Common.Global;
using System.Text;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using AlibabaCloud.TeaUtil.Models;
using Newtonsoft.Json.Linq;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Dysmsapi20170525;

namespace AhCha.Fortunate.Common.Utility
{
    /// <summary>
    /// 发送阿里云短信服务工具类
    /// 安装包：aliyun-net-sdk-core
    /// 模板请勿公开出去，计费的（RMB）
    /// </summary>
    public class AliyunSmsUtil
    {
        #region 阿里云短信发送 V1

        /// <summary>
        /// 阿里云短信服务，官方版本V1
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static bool SendSmsCaptchaV1(string Phone, string Code)
        {
            if (AhChaFortunateGlobalContext.isTest)
            {
                return true;
            }
            string resulr = UnificationSendSms(Phone, "阿里云短信测试", "SMS_154950909", JsonConvert.SerializeObject(new { code = Code }));
            JObject returnRslt = JObject.Parse(resulr);
            if (returnRslt["Message"].ToString() == "OK" && returnRslt["Code"].ToString() == "OK")
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 短信统一发送调用
        /// </summary>
        /// <param name="PhoneNumbers">接收短信的手机号码</param>
        /// <param name="SignName">短信签名名称</param>
        /// <param name="TemplateCode">短信模板CODE</param>
        /// <param name="TemplateParam">短信模板变量对应的实际值</param>
        /// <returns></returns>
        public static string UnificationSendSms(string PhoneNumbers, string SignName, string TemplateCode, string TemplateParam)
        {
            IClientProfile profile = DefaultProfile.GetProfile(regionId: AhChaFortunateGlobalContext.AliyunOssConfig.RegionId, accessKeyId: AhChaFortunateGlobalContext.AliyunOssConfig.AccessKeyId, secret: AhChaFortunateGlobalContext.AliyunOssConfig.AccessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            request.AddQueryParameters("PhoneNumbers", PhoneNumbers);
            request.AddQueryParameters("SignName", SignName);
            request.AddQueryParameters("TemplateCode", TemplateCode);
            request.AddQueryParameters("TemplateParam", TemplateParam);
            CommonResponse response = client.GetCommonResponse(request);
            return Encoding.Default.GetString(response.HttpResponse.Content);
        }

        #endregion

        #region 阿里云短信发送 V2（官方推荐）

        /// <summary>
        /// 阿里云短信服务，官方版本V2
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static bool SendSmsCaptchaV2(string Phone, string Code)
        {
            if (AhChaFortunateGlobalContext.isTest)
            {
                return true;
            }
            return AliyunSmsV2("阿里云短信测试", "SMS_154950909", Phone, JsonConvert.SerializeObject(new { code = Code }));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SignName">短信签名名称</param>
        /// <param name="TemplateCode">短信模板Code</param>
        /// <param name="Phone">接收短信的手机号码</param>
        /// <param name="TemplateParam">短信模板变量对应的实际值，例：{"code":"1234"}</param>
        /// <returns>true/false</returns>
        private static bool AliyunSmsV2(string SignName, string TemplateCode, string Phone, string TemplateParam)
        {
            Client client = CreateClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest
            {
                SignName = SignName,
                TemplateCode = TemplateCode,
                PhoneNumbers = Phone,
                TemplateParam = TemplateParam,
            };
            RuntimeOptions runtime = new RuntimeOptions();
            SendSmsResponse result = client.SendSmsWithOptions(sendSmsRequest, runtime);
            if (result.StatusCode == 200 && result.Body is not null && result.Body.Code == "OK")
            {
                return true; //"短信发送成功";
            }
            throw Oops.Oh(result.Body.Message);
        }


        private static Client CreateClient()
        {
            // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
            // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378671.html。
            Config config = new Config
            {
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                AccessKeyId = AhChaFortunateGlobalContext.AliyunOssConfig.AccessKeyId,//Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                AccessKeySecret = AhChaFortunateGlobalContext.AliyunOssConfig.AccessKeySecret,//Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
            config.Endpoint = "dysmsapi.aliyuncs.com";
            return new Client(config);
        }

        #endregion
    }
}
